package com.laboratory.sselearning.controller;

import com.laboratory.sselearning.service.SseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
@RequestMapping("/sse")
public class SseController {

    @Autowired
    private SseService sseService;

    /**
     * 创建SSE连接
     *
     * @param userId
     * @param timeoutMilliseconds
     * @return
     */
    @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(@RequestParam String userId,
                              @RequestParam(required = false) Long timeoutMilliseconds) {
        return sseService.connect(userId, timeoutMilliseconds);
    }

    /**
     * 发送消息
     *
     * @param userId
     * @param body
     * @return
     */
    @PostMapping("/send/{userId}")
    public String send(@PathVariable String userId, @RequestBody String body) {
        return sseService.sendTo(userId, body) ? "OK" : "OFFLINE";
    }

    /**
     * 广播
     *
     * @param body
     * @return
     */
    @PostMapping("/broadcast")
    public String broadcast(@RequestBody String body) {
        return "DELIVERED=" + sseService.broadcast(body);
    }

    /**
     * 关闭SSE连接
     *
     * @param userId
     */
    @DeleteMapping("/close/{userId}")
    public void close(@PathVariable String userId) {
        sseService.close(userId);
    }

}
